<template>
  <div class="main-layout">
    <header class="header">
      <div class="header-container">
        <div class="logo">
          <router-link to="/">我的博客</router-link>
        </div>
        <nav class="nav">
          <router-link to="/" class="nav-item" exact-active-class="router-link-exact-active">首页</router-link>
          <template v-for="category in categoryStore.categories" :key="category.id">
            <router-link :to="`/category/${category.id}`" class="nav-item">{{ category.name }}</router-link>
          </template>
          <router-link to="/timeline" class="nav-item">时间轴</router-link>
        </nav>
        <div class="user-section">
          <!-- 未登录状态显示登录按钮 -->
          <a-button v-if="!userStore.isLoggedIn" type="primary" @click="showLoginModal" class="login-btn">
            <UserOutlined /> 登录
          </a-button>
          
          <!-- 已登录状态显示用户头像和下拉菜单 -->
          <a-dropdown v-else :trigger="['click']" placement="bottomRight" v-model:visible="dropdownVisible">
            <div class="user-avatar">
              <a-badge :count="unreadNotificationCount" :offset="[5, 5]">
                <img :src="getStaticUrl(userStore.userInfo.avatar)" alt="用户头像">
              </a-badge>
              <span class="user-name">{{ userStore.userInfo?.username || '用户' }}</span>
              <DownOutlined />
            </div>
            
            <template #overlay>
              <div class="custom-dropdown-menu">
                <a-tabs v-model:activeKey="activeTab" class="user-tabs">
                  <a-tab-pane key="menu" tab="菜单">
                    <a-menu class="user-menu">
                      <a-menu-item key="backend">
                        <router-link to="/backend">
                          <FundProjectionScreenOutlined /> 后台管理
                        </router-link>
                      </a-menu-item>
                      <a-menu-item key="profile">
                        <router-link to="/user/profile">
                          <UserOutlined /> 个人资料
                        </router-link>
                      </a-menu-item>
                      <a-menu-item key="articles">
                        <router-link to="/user/articles">
                          <FileTextOutlined /> 我的文章
                        </router-link>
                      </a-menu-item>
                      <a-menu-item key="settings">
                        <router-link to="/user/settings">
                          <SettingOutlined /> 账号设置
                        </router-link>
                      </a-menu-item>
                      <a-menu-divider />
                      <a-menu-item key="logout" @click="handleLogout">
                        <LogoutOutlined /> 退出登录
                      </a-menu-item>
                    </a-menu>
                  </a-tab-pane>
                  
                  <a-tab-pane key="notifications" tab="通知">
                    <NotificationList 
                      @notification-read="updateNotificationCount" 
                      @close-dropdown="dropdownVisible = false"
                    />
                  </a-tab-pane>
                </a-tabs>
              </div>
            </template>
          </a-dropdown>
        </div>
      </div>
    </header>
    
    <!-- 登录模态框 -->
    <a-modal v-model:visible="loginModalVisible" title="登录" @cancel="closeLoginModal" :footer="null" width="400px">
      <a-form :model="loginForm" @finish="handleLogin">
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="loginForm.username" placeholder="用户名">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="loginForm.password" placeholder="密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item name="remember">
          <a-checkbox v-model:checked="loginForm.remember">记住我</a-checkbox>
          <a style="float: right;">忘记密码?</a>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" class="login-button" :loading="loginLoading">登录</a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-form-footer">
        <span>还没有账号? <a @click="showRegisterModal">立即注册</a></span>
      </div>
    </a-modal>
    
    <!-- 注册模态框 -->
    <a-modal v-model:visible="registerModalVisible" title="注册" @cancel="closeRegisterModal" :footer="null" width="400px">
      <a-form :model="registerForm" @finish="handleRegister">
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="registerForm.username" placeholder="用户名">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input v-model:value="registerForm.email" placeholder="邮箱">
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]"
        >
          <a-input-password v-model:value="registerForm.password" placeholder="密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item
          name="confirmPassword"
          :rules="[
            { required: true, message: '请确认密码' },
            { validator: validateConfirmPassword }
          ]"
        >
          <a-input-password v-model:value="registerForm.confirmPassword" placeholder="确认密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" class="login-button" :loading="registerLoading">注册</a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-form-footer">
        <span>已有账号? <a @click="showLoginModal">立即登录</a></span>
      </div>
    </a-modal>
    
    <div class="main-container">
      <div class="content-wrapper">
        <main class="main-content">
          <router-view></router-view>
        </main>
        
        <aside class="sidebar-container">
          <div class="sidebar-fixed">
            <Sidebar />
          </div>
        </aside>
      </div>
    </div>
    
    <footer class="footer">
      <div class="footer-wave">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
          <path fill="#ffffff" fill-opacity="1" d="M0,192L48,176C96,160,192,128,288,122.7C384,117,480,139,576,149.3C672,160,768,160,864,138.7C960,117,1056,75,1152,69.3C1248,64,1344,96,1392,112L1440,128L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path>
        </svg>
      </div>
      
      <div class="footer-content">
        <div class="footer-container">
          <div class="footer-logo">
            <!-- <div class="logo-image">
              <img src="https://via.placeholder.com/80x80" alt="Logo">
            </div> -->
            <div class="logo-text">
              <h2>二次元博客</h2>
              <p>分享技术与动漫的美好世界</p>
            </div>
          </div>
          
          <div class="footer-links">
            <div class="footer-section">
              <h3>快速链接</h3>
              <ul>
                <li><router-link to="/">首页</router-link></li>
                <li><router-link to="/category">分类</router-link></li>
                <li><router-link to="/article/edit">写文章</router-link></li>
                <li><router-link to="/backend">管理后台</router-link></li>
              </ul>
            </div>
            
            <div class="footer-section">
              <h3>联系我们</h3>
              <ul>
                <li><MailOutlined /> example@email.com</li>
                <li><PhoneOutlined /> +86 123 4567 8910</li>
                <li><EnvironmentOutlined /> 东京秋叶原</li>
              </ul>
            </div>
            
            <div class="footer-section">
              <h3>关注我们</h3>
              <div class="social-icons">
                <a href="#" class="social-icon"><GithubOutlined /></a>
                <a href="#" class="social-icon"><TwitterOutlined /></a>
                <a href="#" class="social-icon"><GlobalOutlined /></a>
              </div>
            </div>
          </div>
        </div>
        
        <div class="footer-decoration">
          <div class="character character-left"></div>
          <div class="character character-right"></div>
        </div>
        
        <div class="footer-bottom">
          <p>© 2023 二次元博客 | 保留所有权利 | <a href="/privacy">隐私政策</a> | <a href="/terms">使用条款</a></p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, computed, provide } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useCategoryStore } from '@/stores/category';
import { useUserStore } from '@/stores/user';
import { UserOutlined, LockOutlined, MailOutlined, FileTextOutlined, SettingOutlined, LogoutOutlined, PhoneOutlined, EnvironmentOutlined, GithubOutlined, TwitterOutlined, GlobalOutlined, DownOutlined,FundProjectionScreenOutlined } from '@ant-design/icons-vue';
import { register } from '@/api/auth';
import Sidebar from '@/components/Sidebar.vue';
import notificationWebSocket from '@/utils/websocket';
import NotificationList from '@/components/NotificationList.vue';
import { getUnreadNotificationCount } from '@/api/notification';
import { getStaticUrl } from '@/utils/url';

const router = useRouter();
const categoryStore = useCategoryStore();
const userStore = useUserStore();

// 登录模态框相关
const loginModalVisible = ref(false);
const loginLoading = ref(false);
const loginForm = ref({
  username: '',
  password: '',
  remember: false
});

// 注册模态框相关
const registerModalVisible = ref(false);
const registerLoading = ref(false);
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});

// 提供显示登录模态框的方法
const showLoginModal = () => {
  registerModalVisible.value = false; // 确保注册模态框关闭
  loginModalVisible.value = true;
};

// 提供显示注册模态框的方法
const showRegisterModal = () => {
  loginModalVisible.value = false; // 确保登录模态框关闭
  registerModalVisible.value = true;
};

// 使用provide提供方法给后代组件
provide('showLoginModal', showLoginModal);
provide('showRegisterModal', showRegisterModal);

const activeTab = ref('menu');
const unreadNotificationCount = ref(0);

const fetchUnreadCount = async () => {
  try {
    const count = await getUnreadNotificationCount();
    unreadNotificationCount.value = count;
  } catch (error) {
    console.error('获取未读通知数量失败:', error);
  }
};

const updateNotificationCount = () => {
  if (unreadNotificationCount.value > 0) {
    unreadNotificationCount.value--;
  }
};

// 添加下拉菜单可见性状态
const dropdownVisible = ref(false);

// 监听用户登录状态变化以处理WebSocket连接
watch(() => userStore.isLoggedIn, (isLoggedIn) => {
  console.log('用户登录状态变化:', isLoggedIn);
  if (isLoggedIn && userStore.userInfo && userStore.userInfo.id) {
    // 用户登录后，确保WebSocket连接
    console.log('用户已登录，建立WebSocket连接:', userStore.userInfo.id);
    notificationWebSocket.connect(userStore.userInfo.id);
    fetchUnreadCount();
  } else if (!isLoggedIn) {
    // 用户登出后，关闭WebSocket连接
    console.log('用户已登出，关闭WebSocket连接');
    notificationWebSocket.close();
  }
}, { immediate: true });

// 监听用户信息变化
watch(() => userStore.userInfo, (newUserInfo) => {
  if (userStore.isLoggedIn && newUserInfo && newUserInfo.id) {
    console.log('用户信息已加载，建立WebSocket连接:', newUserInfo.id);
    notificationWebSocket.connect(newUserInfo.id);
    fetchUnreadCount();
  }
}, { deep: true });

onMounted(async () => {
  await categoryStore.fetchCategories();
  
  // 如果用户已登录，获取用户信息后再连接WebSocket
  if (userStore.isLoggedIn) {
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo();
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
    
    if (userStore.userInfo && userStore.userInfo.id) {
      console.log('组件挂载时，用户已登录，建立WebSocket连接:', userStore.userInfo.id);
      notificationWebSocket.connect(userStore.userInfo.id);
      fetchUnreadCount();
    }
  }
  
  // 注册通知处理函数
  notificationWebSocket.on('all', handleNotification);
});

onUnmounted(() => {
  // 组件卸载时移除通知处理函数，但不关闭连接
  notificationWebSocket.off('all', handleNotification);
});

// WebSocket通知处理函数
const handleNotification = (data) => {
  console.log('收到通知:', data);
  fetchUnreadCount();
  message.info(data.message || '您有一条新通知');
};

const closeLoginModal = () => {
  loginModalVisible.value = false;
  loginForm.value = {
    username: '',
    password: '',
    remember: false
  };
};

const closeRegisterModal = () => {
  registerModalVisible.value = false;
  registerForm.value = {
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  };
};

// 验证确认密码
const validateConfirmPassword = async (rule, value) => {
  if (value !== registerForm.value.password) {
    throw new Error('两次输入的密码不一致');
  }
};

const handleLogin = async () => {
  try {
    await userStore.login(loginForm.value);
    message.success('登录成功');
    activeTab.value = 'menu';
    loginModalVisible.value = false;
    
    // 登录成功后，确保WebSocket连接
    if (userStore.userInfo && userStore.userInfo.id) {
      console.log('登录成功，建立WebSocket连接:', userStore.userInfo.id);
      notificationWebSocket.connect(userStore.userInfo.id);
      fetchUnreadCount();
    }
  } catch (error) {
    console.error('登录失败:', error);
    message.error('登录失败，请检查用户名和密码');
  }
};

const handleRegister = async () => {
  try {
    registerLoading.value = true;
    await register({
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password
    });
    message.success('注册成功，请登录');
    // 关闭注册模态框，打开登录模态框
    closeRegisterModal();
    showLoginModal();
  } catch (error) {
    console.error('注册失败:', error);
    message.error('注册失败');
  } finally {
    registerLoading.value = false;
  }
};

const handleLogout = async () => {
  try {
    // 登出前关闭WebSocket连接
    notificationWebSocket.close();
    
    await userStore.logout();
    message.success('退出登录成功');
  } catch (error) {
    console.error('退出登录失败:', error);
    message.error('退出登录失败');
  }
};
</script>

<style scoped>
.main-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.header {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.logo a {
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
  text-decoration: none;
}

.nav {
  display: flex;
  margin-left: 40px;
  gap: 20px;
}

.nav-item {
  color: #333;
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  position: relative;
  padding: 0 4px;
  transition: all 0.3s;
}

/* 只有精确匹配和悬停时才应用激活样式 */
.nav-item:hover, .nav-item.router-link-exact-active {
  color: #42b983;
}

.nav-item:hover::after, .nav-item.router-link-exact-active::after {
  width: 100%;
}

/* 移除非精确匹配的激活样式 */
.nav-item.router-link-active:not(.router-link-exact-active) {
  color: #333;
}

.nav-item.router-link-active:not(.router-link-exact-active)::after {
  width: 0;
}

.nav-item::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #42b983;
  transition: width 0.3s;
}

.main-container {
  flex: 1;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.content-wrapper {
  display: flex;
  gap: 30px;
  flex: 1;
}

.main-content {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.sidebar-container {
  width: 320px;
  flex-shrink: 0;
}

.sidebar-fixed {
  position: sticky;
  top: 20px;
}

.footer {
  position: relative;
  margin-top: 60px;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
  overflow: hidden;
}

.footer-wave {
  position: absolute;
  top: -100px;
  left: 0;
  width: 100%;
  height: 100px;
  z-index: 1;
}

.footer-content {
  position: relative;
  z-index: 2;
  padding-top: 20px;
}

.footer-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 40px;
}

.footer-logo {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.logo-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #f0f0f0;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.logo-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-text h2 {
  margin: 0;
  color: #42b983;
  font-size: 1.8rem;
  font-weight: 700;
}

.logo-text p {
  margin: 5px 0 0;
  color: #666;
  font-size: 0.9rem;
}

.footer-links {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
}

.footer-section {
  min-width: 180px;
}

.footer-section h3 {
  color: #42b983;
  font-size: 1.2rem;
  margin-bottom: 15px;
  position: relative;
  display: inline-block;
}

.footer-section h3::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 30px;
  height: 3px;
  background: linear-gradient(90deg, #42b983, #64b5f6);
  border-radius: 3px;
}

.footer-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-section li {
  margin-bottom: 10px;
}

.footer-section a {
  color: #666;
  text-decoration: none;
  transition: color 0.3s;
  display: inline-block;
  position: relative;
}

.footer-section a::before {
  content: '♥';
  position: absolute;
  left: -18px;
  top: 0;
  color: #ff6b6b;
  opacity: 0;
  transform: scale(0);
  transition: all 0.3s;
}

.footer-section a:hover {
  color: #42b983;
  transform: translateX(5px);
}

.footer-section a:hover::before {
  opacity: 1;
  transform: scale(1);
}

.social-icons {
  display: flex;
  gap: 15px;
}

.social-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  color: #42b983;
  font-size: 1.2rem;
  transition: all 0.3s;
}

.social-icon:hover {
  background-color: #42b983;
  color: white;
  transform: translateY(-5px);
}

.footer-decoration {
  position: relative;
  height: 100px;
  margin-top: 20px;
}

.character {
  position: absolute;
  bottom: 0;
  width: 120px;
  height: 120px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: bottom;
}

.character-left {
  left: 5%;
  background-image: url('https://via.placeholder.com/120x120');
  transform: scaleX(-1);
}

.character-right {
  right: 5%;
  background-image: url('https://via.placeholder.com/120x120');
}

.footer-bottom {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  color: #666;
  font-size: 0.9rem;
  border-top: 1px solid #eee;
}

.footer-bottom a {
  color: #42b983;
  text-decoration: none;
}

/* 调整图标样式 */
.anticon {
  margin-right: 8px;
}

.user-section {
  display: flex;
  align-items: center;
}

.login-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background-color: #42b983;
  border-color: #42b983;
}

.login-btn:hover {
  background-color: #3da776;
  border-color: #3da776;
}

.icon-user::before {
  content: '👤';
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-name {
  margin-left: 8px;
  font-weight: 500;
  color: #333;
}

.icon-dropdown {
  margin-left: 4px;
  font-size: 12px;
  color: #999;
}

.icon-dropdown::after {
  content: '▼';
  font-size: 8px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.forgot-password {
  color: #42b983;
  text-decoration: none;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  color: #666;
}

.register-link a {
  color: #42b983;
  text-decoration: none;
  cursor: pointer;
}

/* 下拉菜单图标 */
.icon-profile::before { content: '👤'; margin-right: 8px; }
.icon-articles::before { content: '📝'; margin-right: 8px; }
.icon-settings::before { content: '⚙️'; margin-right: 8px; }
.icon-logout::before { content: '🚪'; margin-right: 8px; }

@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .sidebar-container {
    width: 100%;
  }
  
  .sidebar-fixed {
    position: static;
  }
  
  .footer-container {
    flex-direction: column;
    gap: 30px;
  }
  
  .footer-links {
    flex-direction: column;
    gap: 30px;
  }
  
  .character {
    width: 80px;
    height: 80px;
  }
  
  .user-name {
    display: none;
  }
}

/* 添加登录/注册表单样式 */
.login-button {
  width: 100%;
}

.login-form-footer {
  text-align: center;
  margin-top: 16px;
}

.login-form-footer a {
  color: #1890ff;
  cursor: pointer;
}

.login-form-footer a:hover {
  color: #40a9ff;
}

/* 修复下拉菜单样式 */
.custom-dropdown-menu {
  min-width: 320px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  overflow: hidden;
}

.user-tabs {
  margin: 0;
  padding: 0;
}

:deep(.ant-tabs-tab) {
  padding: 12px 16px !important;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 0 !important;
}

:deep(.ant-tabs-content) {
  max-height: 400px;
  overflow-y: auto;
}

.user-menu {
  border-right: none;
}

:deep(.notification-item) {
  padding: 10px 16px;
}

:deep(.notification-icon) {
  width: 32px;
  height: 32px;
  font-size: 16px;
}

:deep(.notification-content) {
  padding-right: 5px;
}

:deep(.notification-message) {
  font-size: 13px;
  line-height: 1.4;
}

:deep(.notification-time) {
  font-size: 11px;
}
</style> 